<script setup name="customer">
import { ref } from 'vue'
import Form from './form.vue'
import LookFrom from './look.vue'
import EditForm from './edit.vue'
import auditHistory from './auditHistory.vue'
import auditHistory1 from './auditHistory1.vue'

import Table from './table.vue'
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  DelDataAPI,
  GetDetailAPI,
  ToExamineAPI,
  RevokeAPI,
  ReviewSubmitAPI,
  uploadSolutionAPI,
  FangAnExamineAPI
} from '@/api/order/sale/complaints'
const { proxy } = getCurrentInstance()

// 封装 方法 字典查询
const {
  customer_level, // 等级
  customer_affiliated_organization //所属机构
} = proxy.useDict('customer_level', 'customer_affiliated_organization')

const FormRef = ref(null)

const TableRef = ref(null)

const BtnLoading = ref(false)
// 新增弹窗状态
const addIsShow = ref(false)

// 审核弹窗状态
const examineIsShow = ref(false)

// 上传解决方案弹窗状态
const upSolutionShow = ref(false)

// 方案审核弹窗状态
const SolutionShow = ref(false)

// 查看弹窗状态
const lookShow = ref(false)

// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

//
const Ids = ref([])
const rows = ref([])

// 查询条件
const SelectList = ref([
  { type: '日期范围' },
  { label: '物料编码', model: 'materialCode', type: '输入框', placeholder: '请输入物料编码' },
  { label: '客户名称', model: 'customerName', type: '输入框', placeholder: '请输入客户名称' },
  { label: '开单人', model: 'createBy', type: '输入框', placeholder: '请输入开单人' },
  { label: '销售发货单号', model: 'salesDocumentNum', type: '输入框', placeholder: '请输入销售发货单号' }
])

// 新增字段
const ruleForm = reactive({
  customerId: '', // 客户id
  customerDict: '', // 客户
  materialId: '', // 物料id
  materialCode: '', // 物料编码
  batchNum: '', // 批次号
  orderType: '', // 订单类型
  salesDocumentNum: '', //销售发货单号
  complaints: '', //投诉问题
  enclosureUrl: '' // 附件
})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 50
})

/**
 * 弹窗
 */
const add = () => {
  title.value = '新增'
  addIsShow.value = true
}

const edit = async val => {
  try {
    proxy.$modal.loading('请稍候...')

    title.value = '修改'
    const res = await GetDetailAPI(val.id)

    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    ruleForm.customerReviewStatus = val.customerReviewStatus
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 客诉审核
const examine = async () => {
  try {
    const Obj = rows.value[0]
    if (Obj.customerReviewStatus != 2 && Obj.customerReviewStatus != 3)
      return proxy.warningMsg('此操作仅为待审核状态可用')
    proxy.$modal.loading('请稍候...')
    title.value = '审核'
    const res = await GetDetailAPI(Obj.id)
    if (res.code !== 200) return (Btnloading.value = false)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    // 审核弹窗
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 上传解决方案 弹窗
const upSolution = async () => {
  const Obj = rows.value[0]
  if (rows.value[0].customerReviewStatus != 4) return proxy.warningMsg('只能为上传解决方案状态时可用！')
  try {
    proxy.$modal.loading('请稍候...')

    const res = await GetDetailAPI(Obj.id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    // 上传解决弹窗
    upSolutionShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 方案审核
const schemeExamine = async () => {
  const Obj = rows.value[0]
  if (Obj.customerReviewStatus != 5 && Obj.customerReviewStatus != 7) return proxy.warningMsg('只能为待方案审核时使用')
  try {
    proxy.$modal.loading('请稍候...')

    const res = await GetDetailAPI(Obj.id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    // 上传解决弹窗
    SolutionShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  rows.value = selection

  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
handleSelectionChange([])

// 新增
const addSubmit = async () => {
  const FormRefisif = await FormRef.value.submit()
  // const TableRefisif = await TableRef.value.submit()

  if (!FormRefisif) return
  // if (!TableRefisif) return

  for (let key in FormRefisif) {
    ruleForm[key] = FormRefisif[key]
  }

  // ruleForm.materialId = TableRefisif[0].materialId
  // ruleForm.orderType = TableRefisif[0].materialType
  // ruleForm.complaintsList = TableRefisif
  Btnloading.value = true
  const res = await AddDataAPI(ruleForm)
  if (res.code !== 200) return (Btnloading.value = false)
  proxy.successMsg('添加成功')

  close()
}

// 修改
const EditSub = async () => {
  const FormRefisif = await FormRef.value.submit()
  if (!FormRefisif) return
  for (let key in FormRefisif) {
    ruleForm[key] = FormRefisif[key]
  }

  Btnloading.value = true
  const res = await EditDataAPI(ruleForm)
  if (res.code !== 200) return
  proxy.successMsg('修改成功')
  close()
}

// 审核同意 || 不同意  （同意1 不同意 2
const yesAndNo = async val => {
  const isif = await FormRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      id: Ids.value[0],
      isAdopt: val
    }
    await ToExamineAPI(form)
    close()
    getList()

    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 方案审核 || 不同意  （同意1 不同意 2
const solutionIs = async val => {
  const isif = await FormRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      id: Ids.value[0],
      isAdopt: val
    }
    await FangAnExamineAPI(form)
    examineIsShow.value = false
    getList()
    close()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 提交审核
const subExamine = async () => {
  if (rows.value[0].customerReviewStatus != 1) return proxy.warningMsg('只能对待提交的客诉进行提交审核')
  const MesBox = await proxy.FreezMessageBox('是否确定提交审核？')
  if (!MesBox) return
  await ReviewSubmitAPI(Ids.value[0])
  proxy.successMsg('操作成功')
  close()
  getList()
}

// 撤销审核
const revoke = async () => {
  const Obj = rows.value[0]
  if (Obj.customerReviewStatus != 2) return proxy.warningMsg('只能为待审核时使用')
  const MesBox = await proxy.FreezMessageBox('是否确定撤销审核？')
  if (!MesBox) return
  await RevokeAPI(Ids.value[0])
  proxy.successMsg('操作成功')
  close()
  getList()
}

// 提交上传方案
const upSolutionSub = async () => {
  const FormRefisif = await FormRef.value.submit()
  if (!FormRefisif) return
  for (let key in FormRefisif) {
    ruleForm[key] = FormRefisif[key]
  }
  ruleForm.customerComplaintsId = FormRefisif.id
  await uploadSolutionAPI(ruleForm)
  proxy.successMsg('操作成功')
  close()
  getList()
}

// 删除
const del = async val => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  await DelDataAPI(Ids.value.length <= 0 ? val : Ids.value.join(','))
  close()
  proxy.successMsg('删除成功')
}

// 查看
const dxamine = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '查看'
    const res = await GetDetailAPI(val.id)
    for (let Key in res.data) {
      ruleForm[Key] = res.data[Key]
    }
    lookShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 新增修改弹窗关闭时
const close = () => {
  addIsShow.value = false
  upSolutionShow.value = false
  examineIsShow.value = false
  SolutionShow.value = false
  lookShow.value = false
  for (let KEY in ruleForm) {
    ruleForm[KEY] = ''
  }
  getList()
}

// 条件查询
const selectSubmit = Obj => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    TableData.value = res.rows
    total.value = res.total
    loading.value = false
  } catch (error) {
  } finally {
    loading.value = false
  }
}
getList()

const tableHeight = ref(0)

const maxHeight = computed(() => {
  const windowHeight = window.innerHeight
  const headerHeight = 310
  const paginationHeight = 0
  return windowHeight - headerHeight - paginationHeight
})

const handleResize = () => {
  tableHeight.value = maxHeight.value
}

onMounted(() => {
  tableHeight.value = maxHeight.value
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <el-button type="primary" v-hasPermi="['order:sale:complaints:add']" @click="add">新增</el-button>
      <el-button
        type="warning"
        v-hasPermi="['order:sale:complaints:subExamine']"
        :disabled="ExamineDisabled"
        @click="subExamine"
        >提交审核</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:sale:complaints:examine']"
        :disabled="ExamineDisabled"
        @click="examine"
        >客诉审核</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:sale:complaints:revoke']"
        :disabled="ExamineDisabled"
        @click="revoke"
        >撤销审核</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:sale:complaints:upSolution']"
        :disabled="ExamineDisabled"
        @click="upSolution"
        >上传解决方案</el-button
      >
      <el-button
        type="primary"
        v-hasPermi="['order:sale:complaints:schemeExamine']"
        :disabled="ExamineDisabled"
        @click="schemeExamine"
        >方案审核</el-button
      >
      <el-button type="danger" v-hasPermi="['order:sale:complaints:remove']" :disabled="DelDisabled" @click="del"
        >删除</el-button
      >

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        stripe
        border
        :data="TableData"
        class="tableClass"
        @selection-change="handleSelectionChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="客户名称" prop="customerName" width="120" />
        <el-table-column label="客诉审核状态" align="center" width="120">
          <template #default="scope">
            <div>
              <p-tag bgc="#006cb6" text="待提交" v-if="scope.row.customerReviewStatus == 1" />
              <p-tag bgc="#fbc82f" text="待审核" v-else-if="scope.row.customerReviewStatus == 2" />
              <p-tag bgc="#f28e16" text="审核中" v-else-if="scope.row.customerReviewStatus == 3" />
              <p-tag bgc="#c17cc3" text="待上传方案" v-else-if="scope.row.customerReviewStatus == 4" />
              <p-tag bgc="#fbc82f" text="待方案审核" v-else-if="scope.row.customerReviewStatus == 5" />
              <p-tag bgc="#ff0000" text="方案未通过" v-else-if="scope.row.customerReviewStatus == 6" />
              <p-tag bgc="#f28e16" text="方案审核中" v-else-if="scope.row.customerReviewStatus == 7" />
              <p-tag bgc="#bebebe" text="已完成" v-else-if="scope.row.customerReviewStatus == 8" />
              <p-tag bgc="#ff0000" text="客诉未通过" v-else />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="物料编码" prop="materialCode" width="120" />
        <el-table-column label="物料名称" prop="materialName" width="120" />
        <el-table-column label="销售发货单号" prop="salesDocumentNum" width="120" show-overflow-tooltip />
        <el-table-column label="开单人" prop="createBy" width="120" />
        <el-table-column label="开单时间" prop="createTime" width="180" />
        <el-table-column label="审核人" prop="customerReviewBy" width="auto" />
        <el-table-column label="客诉审核时间" prop="customerReviewTime" width="180" />
        <el-table-column label="方案审核人" prop="programmeReviewBy" width="auto" show-overflow-tooltip />
        <el-table-column label="方案审核时间" prop="programmeReviewTime" width="180" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link
                v-hasPermi="['order:sale:complaints:edit']"
                type="primary"
                text="修改"
                v-show="
                  scope.row.customerReviewStatus == 1 ||
                  scope.row.customerReviewStatus == 6 ||
                  scope.row.customerReviewStatus == 9
                "
                @click="edit(scope.row)"
              />
              <el-link
                v-hasPermi="['order:sale:complaints:remove']"
                type="primary"
                v-show="scope.row.customerReviewStatus == 1"
                text="删除"
                @click="del(scope.row.id)"
              />
              <el-link
                type="primary"
                v-hasPermi="['order:sale:complaints:query']"
                text="查看"
                @click="dxamine(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" @close="close" width="50%">
      <template #body>
        <EditForm
          ref="FormRef"
          :data="ruleForm"
          :disabled="ruleForm.customerReviewStatus == 1 || ruleForm.customerReviewStatus == 9"
          v-if="title == '修改'"
        />
        <Form ref="FormRef" :data="ruleForm" :upload="title == '上传解决方案'" v-else />
        <!-- 按钮 -->
        <div class="flex-between">
          <div></div>
          <div>
            <el-button :loading="BtnLoading" type="primary" @click="title == '新增' ? addSubmit() : EditSub()"
              >保存</el-button
            >
            <el-button @click="close">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 审核弹窗 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" :title="title" @close="close" width="50%">
      <template #body>
        <AuditHistory :auditDoc="rows[0].salesDocumentNum" perms="order:sale:complaints:review">
          <template #body>
            <div>
              <Form ref="FormRef" :title="title" :data="ruleForm" disabled :examine="title == '审核'" />
              <div class="Btn">
                <el-button type="danger" @click="yesAndNo(2)">不同意</el-button>
                <el-button type="success" @click="yesAndNo(1)">同意</el-button>
                <el-button type="inof" @click="close">取消</el-button>
              </div>
            </div>
          </template>
        </AuditHistory>
      </template>
    </p-XiaoheDialog>
    <!-- 上传解决方案 -->
    <p-XiaoheDialog :dialogVisible="upSolutionShow" title="上传解决方案" @close="close" width="50%">
      <template #body>
        <Form ref="FormRef" :data="ruleForm" disabled upload />
        <!-- 按钮 -->
        <div class="flex-between">
          <div></div>
          <div>
            <el-button :loading="BtnLoading" type="primary" @click="upSolutionSub">保存</el-button>
            <el-button @click="close">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 方案审核 -->
    <p-XiaoheDialog :dialogVisible="SolutionShow" title="方案审核" @close="close" width="50%">
      <template #body>
        <auditHistory1 :auditDoc="ruleForm">
          <template #body>
            <Form ref="FormRef" examine :data="ruleForm" disabled upload Solution />
          </template>
        </auditHistory1>

        <!-- 按钮 -->
        <div class="flex-between">
          <div></div>
          <div class="Btn">
            <el-button type="danger" @click="solutionIs(2)">不同意</el-button>
            <el-button type="success" @click="solutionIs(1)">同意</el-button>
            <el-button type="inof" @click="close">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 查看 -->
    <p-XiaoheDialog :dialogVisible="lookShow" title="查看" @close="close" width="50%">
      <template #body>
        <auditHistory :auditDoc="ruleForm">
          <template #body>
            <LookFrom ref="FormRef" :data="ruleForm" upload disabled :title="title" />
          </template>
        </auditHistory>
      </template>
    </p-XiaoheDialog>
  </div>
</template>

<style scoped lang="scss">
.Btn {
  float: right;
}
</style>
